package snapex.user.controller;

import java.io.ByteArrayOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.ldap.userdetails.LdapUserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import snapex.core.SnapexApplicationException;
import snapex.core.model.User;
import snapex.core.security.AuthenticationManagerBuilderDelegate;
import snapex.core.utils.QRCodeUtil;


@Slf4j
@Controller
@RequestMapping
public class UserQRCodeController {
	@Autowired
	AuthenticationManagerBuilderDelegate builder;
	
	@Value("${snapex.weixinUrl}")
	String weixinUrl;
		
	@ApiOperation(value = "QR code for wechat")
	@GetMapping(value = "/weixin/qrcode", produces = MediaType.IMAGE_JPEG_VALUE)
	public ResponseEntity<byte[]> weixinQRCode() throws Exception {
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth == null) {
			throw new SnapexApplicationException("Authentication is required");
		}

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		
		String url = new StringBuilder()
				.append(weixinUrl)
				.toString();
		
		QRCodeUtil.encode(url, output);
		
		return new ResponseEntity(output.toByteArray(), HttpStatus.OK);
	}

	@ApiOperation(value = "QR code for wechat")
	@GetMapping(value = "/weixin/param", produces = MediaType.IMAGE_JPEG_VALUE)
	public ResponseEntity<byte[]> weixinParamQRCode() throws Exception {
		
		log.debug("***/weixin/param***");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth == null) {
			throw new SnapexApplicationException("Authentication is required");
		}
		
		String userId = "";
		if(auth.getPrincipal() instanceof LdapUserDetails) {
			userId = ((LdapUserDetails)auth.getPrincipal()).getUsername();
		}else {
			userId = ((User)auth.getPrincipal()).getUsername();
		}	
				
		String hashUserId =  DigestUtils.md5DigestAsHex(userId.getBytes());
				
		String params = hashUserId.substring(0, 10) + System.currentTimeMillis() + hashUserId.substring(10);
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		
		QRCodeUtil.encode(params, output);
		
		return new ResponseEntity(output.toByteArray(), HttpStatus.OK);
	}

}